<template>
    <div>
        <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 功能区  搜索+添加 -->
        <el-card class="box-card">
            <!-- gutter:列与列之间的间隔 -->
            <!-- span:每一列占有的宽度   整个屏幕的宽度被设计为24 -->
            <el-row :gutter="20">
                <el-col :span="8"> <!-- 占据屏幕的1/3 -->
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" :clearable="true" @clear="getUserList">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="4"> <!-- 占据屏幕的1/6 -->
                    <el-button type="primary"  @click="addUserDialogVisible=true">添加用户</el-button>
                </el-col>
            </el-row>
        </el-card>
        <!-- 添加用户对话框 -->
        <el-dialog title="添加用户信息" :visible.sync="addUserDialogVisible" width="40%" @close="addDialogClosed">
            <el-form ref="addFormRef" :rules="addFormRules" :model="addForm" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <!-- 功能区 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addUserDialogVisible=false">取消</el-button>
                <el-button type="primary" @click="addUser">确定</el-button>
            </span>
        </el-dialog>



        <!-- 信息展示区 -->
        <!-- el-table可以自动解析json数据,渲染表格 
           它可以将json数据的每个关键字对应每一列,有几个json对象就渲染几行-->
        <el-table :data="userList" width="100%" border>
            <el-table-column label="序号" type="index" width="80"></el-table-column>
            <el-table-column label="用户名" prop="UserName"></el-table-column>
            <el-table-column label="手机" prop="Mobile"></el-table-column>
            <el-table-column label="邮箱" prop="Email"></el-table-column>
            <el-table-column label="角色" prop="RoleName"></el-table-column>
            <el-table-column label="状态" prop="MgState">
                <template slot-scope="scope">
                    <!-- 拿到当前所在行的对象的MgState属性 -->
                    <el-switch v-model="scope.row.MgState" active-color="#13ce66" inactive-color="#ddd"
                        @change="userStateChanged(scope.row)"></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template>
                    <el-button type="success" size="mini">修改</el-button>
                    <el-button type="info" size="mini">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页查询功能条 -->
        <!--  @size-change  页面条数改变触发函数   @current-change:页码改变的触发函数
           current-page:第一次查询的页码  page-size:第一次查询的页面条数
           page-sizes:页面条数的种类  layout：功能布局-->
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page="queryInfo.pagenum" :page-size="queryInfo.pagesize" :page-sizes="[2, 5, 10]"
            layout="total,sizes,prev,pager,next,jumper" :total="total">
        </el-pagination>
    </div>
</template>

<script>
export default {
    data() {
        //自定义验证邮箱规则
        var checkEmail = (rule,value,callback) =>{
            //正则表达式邮箱
            const regEmail = 
                /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/
            if(regEmail.test(value)){
                //合法邮箱
                callback()
            }
            callback(new Error('请输入合法的邮箱地址！'))
        } 
        //自定义验证手机号码规则
        var checkMobile = (rule,value,callback) =>{
            //正则表达式手机
            const regMobile = /^1[3456789]\d{9}$/
            if(regMobile.test(value)){
                callback()
            }
            callback(new Error('请输入合法的手机号码！'))
        }


        return {
            queryInfo: { query: "", pagenum: 0, pagesize: 2 }, //分页查询条件:   关键字,页码,当前页条数   根据分页查询公式,得到某一页的数据
            userList: [],  //查出来的结果   用户数据列表
            total: 0,  //总数
            //添加用户对话框涉及变量
            addUserDialogVisible: false,  //控制对话框的显隐
            addForm: { //表单对象
                username: "",
                password: "",
                email: "",
                mobile: ""
            },
            addFormRules: {  //表单校验规则
                username:[  //用户名
                    {required:true,message:"请输入用户名",trigger:"blur"},//子规则1
                    {min:3,max:10,message:"长度在3到10个字符",trigger:"blur"} //子规则2
                ],
                password:[  //密码
                    {required:true,message:"请输入密码",trigger:"blur"},//子规则1
                    {min:6,max:15,message:"长度在6到15个字符",trigger:"blur"} //子规则2
                ],
                email:[  //邮箱规则
                    {required:true,message:"请输入邮箱地址",trigger:"blur"},//子规则1
                    {validator:checkEmail,trigger:"blur"}
                ],
                mobile:[  //电话规则
                    {required:true,message:"请输入手机号码",trigger:"blur"},//子规则1
                    {validator:checkMobile,trigger:"blur"}
                ],
            }
        }
    },
    methods: {
        async getUserList() {
            const res = await this.$http.get('/api/users', {
                params: this.queryInfo
            })
            this.userList = (res.data).data  //查询出来的用户列表赋值给userList
            // console.log(this.userList)
            this.total = (res.data).total
        },
        handleSizeChange(newsize) {  //页面条数改变的函数
            this.queryInfo.pagesize = newsize
            this.getUserList()
        },
        handleCurrentChange(newpage) {  //页码改变的函数
            this.queryInfo.pagenum = newpage
            this.getUserList()
        },
        async userStateChanged(userinfo) {  //开关组件改变时的函数
            const res = await this.$http.get('/api/userupdate', { params: userinfo })
            if (res.data.count <= 0) return //如果一条信息都没改，就直接停止
            //弹个小绿窗
            this.$message.success(res.data.count + '个状态信息已经修改成功！目前的状态的值为：' + res.data.newState)
        },
        addDialogClosed(){  //关闭对话框的时候调用
            this.$refs.addFormRef.resetFields()             //清空表单
        },
        addUser(){  //添加用户
            //向表单添加一些属性，一并带到后台去
            this.addForm['query'] = this.queryInfo.query
            this.addForm['pagenum'] = this.queryInfo.pagenum
            this.addForm['pagesize'] = this.queryInfo.pagesize

            this.$refs.addFormRef.validate(async valid=>{  //把规则跑一遍
                if(valid){  //如果数据合规
                    const res = await this.$http.get('/api/adduser',{
                        params:this.addForm
                    })
                    this.userList = res.data.data  //从后台拿到新的用户列表
                    this.total = res.data.total   //从后台拿到新的用户列表总长度
                    this.addUserDialogVisible = false   //添加成功以后，关闭添加用户对话框
                    this.$message.success('添加用户成功')  //弹个小绿窗
                }
            })
        }
    },
    created() {
        this.getUserList()
    }
}
</script>

<style scoped>
.el-table {
    margin-top: 10px;

}

.el-pagination {
    margin-top: 5px;
    text-align: left;
}
</style>